﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using AIStudio.Wpf.EasyTileManager.Utils;

namespace AIStudio.Wpf.EasyTileManager.Controls
{
    /// <summary>
    /// 按照步骤 1a 或 1b 操作，然后执行步骤 2 以在 XAML 文件中使用此自定义控件。
    ///
    /// 步骤 1a) 在当前项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 
    /// 元素中: 
    ///
    ///     xmlns:MyNamespace="clr-namespace:AIStudio.Wpf.EasyTileManager.Controls"
    ///
    ///
    /// 步骤 1b) 在其他项目中存在的 XAML 文件中使用该自定义控件。
    /// 将此 XmlNamespace 特性添加到要使用该特性的标记文件的根 
    /// 元素中: 
    ///
    ///     xmlns:MyNamespace="clr-namespace:AIStudio.Wpf.EasyTileManager.Controls;assembly=AIStudio.Wpf.EasyTileManager.Controls"
    ///
    /// 您还需要添加一个从 XAML 文件所在的项目到此项目的项目引用，
    /// 并重新生成以避免编译错误: 
    ///
    ///     在解决方案资源管理器中右击目标项目，然后依次单击
    ///     “添加引用”->“项目”->[浏览查找并选择此项目]
    ///
    ///
    /// 步骤 2)
    /// 继续操作并在 XAML 文件中使用控件。
    ///
    ///     <MyNamespace:TileWidget/>
    ///
    /// </summary>
    ///     [TemplatePart(Name = "PART_DragThumb", Type = typeof(DragThumb))]
    //[TemplatePart(Name = "PART_ResizeDecorator", Type = typeof(Control))]
    //[TemplatePart(Name = "PART_ConnectorDecorator", Type = typeof(Control))]
    //[TemplatePart(Name = "PART_ContentPresenter", Type = typeof(ContentPresenter))]
    public class TileWidget : Control
    {
        static TileWidget()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(TileWidget), new FrameworkPropertyMetadata(typeof(TileWidget)));
        }

        public TileWidget()
        {
            this.Loaded += new RoutedEventHandler(TileWidget_Loaded);
        }

        private void TileWidget_Loaded(object sender, RoutedEventArgs e)
        {
            if (base.Template != null)
            {
                Button ToggleMaximized = this.Template.FindName("ToggleMaximized", this) as Button;
                Button ToggleExpandCollapse = this.Template.FindName("ToggleExpandCollapse", this) as Button;

                ToggleMaximized.Click += new RoutedEventHandler(ToggleMaximized_Click);
                ToggleExpandCollapse.Click += new RoutedEventHandler(ToggleExpandCollapse_Click);

            }
        }

        protected override void OnPreviewMouseDown(MouseButtonEventArgs e)
        {
            base.OnPreviewMouseDown(e);

            if (e.ClickCount == 2 && e.RightButton == MouseButtonState.Pressed)
            {
                RaiseEvent(new RoutedEventArgs(MaximizedClickRoutedEvent));
                e.Handled = true;
            }

            e.Handled = false;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            if (e.LeftButton == MouseButtonState.Pressed)
            {
                MouseEventArgs args = new MouseEventArgs(e.MouseDevice, e.Timestamp, e.StylusDevice);
                args.RoutedEvent = TileMouseMoveEvent;
                RaiseEvent(args);
            }
        }

        protected override void OnDragLeave(DragEventArgs e)
        {
            base.OnDragLeave(e);

            Border border = this.Template.FindName("border", this) as Border;
            if (border != null)
            {
                border.Background = (Brush)this.Resources["TileBaseFillKey"];
            }

            e.Handled = false;
        }

        protected override void OnDragEnter(DragEventArgs e)
        {
            base.OnDragEnter(e);
            Border border = this.Template.FindName("border", this) as Border;
            if (border != null)
            {
                border.Background = (Brush)this.Resources["TileSwapTargetBgBrushFillKey"];
            }

            e.Handled = false;
        }

        protected override void OnDrop(DragEventArgs e)
        {
            base.OnDrop(e);

            Border border = this.Template.FindName("border", this) as Border;
            if (border != null)
            {
                border.Background = (Brush)this.Resources["TileBaseFillKey"];
            }

            e.Handled = false;
        }

        private void ToggleMaximized_Click(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(MaximizedClickRoutedEvent));
        }

        private void ToggleExpandCollapse_Click(object sender, RoutedEventArgs e)
        {
            RaiseEvent(new RoutedEventArgs(ExpandClickRoutedEvent));
        }


        #region 依赖属性

        /// <summary>
        /// 窗体标题
        /// </summary>
        public string Title
        {
            get { return (string)GetValue(TitleProperty); }
            set { SetValue(TitleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register("Title", typeof(string), typeof(TileWidget), new PropertyMetadata(string.Empty));


        public object Content
        {
            get { return (object)GetValue(ContentProperty); }
            set { SetValue(ContentProperty, value); }
        }

        // Using a DependencyProperty as the backing store for Content.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ContentProperty =
            DependencyProperty.Register("Content", typeof(object), typeof(TileWidget), 
                new FrameworkPropertyMetadata(null, 
                    FrameworkPropertyMetadataOptions.AffectsRender | 
                    FrameworkPropertyMetadataOptions.AffectsParentArrange));

        /// <summary>
        /// 当前瓦片状态
        /// </summary>
        public TileState CurrentTileState
        {
            get { return (TileState)GetValue(CurrentTileStateProperty); }
            set { SetValue(CurrentTileStateProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CurrentTileState.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CurrentTileStateProperty =
            DependencyProperty.Register("CurrentTileState", typeof(TileState), typeof(TileWidget), new PropertyMetadata(TileState.Normal));

        static void OnCurrentTileStateChanged(DependencyObject property, DependencyPropertyChangedEventArgs args)
        {

            if (Equals(args.NewValue, args.OldValue))
            {
                return;

            }

            TileState result = TileState.Normal;

            if (Enum.TryParse(args.NewValue.ToString(), out result))
            {
                TileWidget control = property as TileWidget;

                Button ToggleMaximized = control.Template.FindName("ToggleMaximized", control) as Button;
                Button ToggleExpandCollapse = control.Template.FindName("ToggleExpandCollapse", control) as Button;
                switch (result)
                {
                    case TileState.Maximized:
                        {
                            if (ToggleMaximized != null)
                            {
                                ToggleMaximized.Visibility = Visibility.Collapsed;
                            }

                            if (ToggleExpandCollapse != null)
                            {
                                ToggleExpandCollapse.Visibility = Visibility.Collapsed;
                            }
                        }
                        break;
                    case TileState.Normal:
                    case TileState.Minimized:
                    case TileState.MinimizedExpanded:
                    default:
                        {
                            if (ToggleMaximized != null)
                            {
                                ToggleMaximized.Visibility = Visibility.Visible;
                            }

                            if (ToggleExpandCollapse != null)
                            {
                                ToggleExpandCollapse.Visibility = Visibility.Visible;
                            }
                        }
                        break;
                }
            }
        }

        #endregion

        #region 路由事件

        public static readonly RoutedEvent MaximizedClickRoutedEvent = EventManager.RegisterRoutedEvent(
            "MaximizedClickRoutedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TileWidget));

        //
        // 摘要:
        //     在单击 最大化按钮 时发生。
        public event RoutedEventHandler MaximizedClick
        {
            add { base.AddHandler(MaximizedClickRoutedEvent, value); }
            remove { base.RemoveHandler(MaximizedClickRoutedEvent, value); }
        }

        public static readonly RoutedEvent ExpandClickRoutedEvent = EventManager.RegisterRoutedEvent(
            "ExpandClickRoutedEvent", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(TileWidget));

        //
        // 摘要:
        //     在单击 折叠按钮 时发生。
        public event RoutedEventHandler ExpandClick
        {
            add { base.AddHandler(ExpandClickRoutedEvent, value); }
            remove { base.RemoveHandler(ExpandClickRoutedEvent, value); }
        }

        public static readonly RoutedEvent TileMouseMoveEvent = EventManager.RegisterRoutedEvent(
            "TileMouseMoveEvent", RoutingStrategy.Bubble, typeof(MouseEventHandler), typeof(TileWidget));

        //
        // 摘要:
        //     在 titleGrid上移动鼠标 时发生。
        public event MouseEventHandler TileMouseMove
        {
            add
            {
                AddHandler(TileMouseMoveEvent, value, false);
            }
            remove
            {
                RemoveHandler(TileMouseMoveEvent, value);
            }
        }

        #endregion

    }
}
